package com.atguigu.doc;

import com.atguigu.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * create by undeRdoG on  2021-06-21  21:21
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class ESTest_Doc_Insert {

    public static void main(String[] args) throws IOException {
        //  创建ES 客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200))
        );

        IndexRequest  request = new IndexRequest();
        request.index("user")    //  索引名称
                .id("1001");      //  自定义主键

        User user = new User();
        user.setName("张三");
        user.setSex("男");
        user.setAge(30);

        // 向ES 插入数据，必须转成 json 格式

        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);

        // 封装数据
        request.source(userJson, XContentType.JSON);

        // 插入数据
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);

        System.out.println(response.getResult());


    }
}
